#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include <signal.h>
#include <functional>

#include "log.hpp"
#include "protocol.hpp"

namespace server
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR,
    };

    static const uint16_t gport = 8080;
    static const int gbacklog = 5;

    // const Request& req 输入型参数    Response& resp 输出型参数
    typedef std::function<bool(const Request &req, Response &resp)> func_t;

    bool handlerEntery(int sock, func_t func)
    {
        std::string inbuffer;
        while (true)
        {
            // 1. 读取数据，保证是完整的
            // 先做判断，保证报文里是一个完整的请求
            std::string req_text;
            if (!recvPackage(sock, inbuffer, &req_text))
                return false;
            std::cout << "带报头的请求：\n " << req_text << std::endl;
            
            // 可以开始处理
            std::string req_str;
            if (!deLength(req_text, &req_str))
                return false;
            std::cout << "去报头的正文：\n " << req_text << std::endl;

            // 2. 反序列化
            Request req;
            if (!req.deserialize(req_str))
                return false;

            // 3. 计算处理  -- 业务逻辑
            Response resp;
            func(req, resp);

            // 4. 对响应Response进行序列化
            std::string resp_str;
            resp.serialize(&resp_str);

            std::cout << "计算完成，序列化响应：" << resp_str<< std::endl;


            // 5. 发送响应
            std::string send_string = enLength(resp_str);
            std::cout << "构建完成完整的响应" << send_string << std::endl;

            send(sock, send_string.c_str(), send_string.size(), 0);
        }
    }

    class CalServer
    {
    public:
        CalServer(const uint16_t &port = gport)
            : _listensock(-1), _port(port)
        {
        }

        void initServer()
        {
            // 1. 创建tcp socket套接字
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "create socket error");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "create socket success: %d", _listensock);

            // 2. bind绑定自己的网络信息
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = INADDR_ANY;
            if (bind(_listensock, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                logMessage(FATAL, "bind socket error");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "bind socket success");

            // 3. 设置socket为监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                logMessage(FATAL, "listen socket error");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "listen socket success");
        }

        void start(func_t func)
        {
            for (;;)
            {
                // 4. server 获取新链接
                // sock，和client进行通信的fd
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(ERROR, "accept error, next");
                    continue;
                }
                logMessage(NORMAL, "accept a new link success, get new sock: %d", sock);
                std::cout << "sock: " << sock << std::endl;

                // version 2 多进程版-1 孙子进程版
                pid_t id = fork();
                if (id == 0)
                {
                    // 子进程
                    close(_listensock); // 关闭不需要的接口
                    if (fork() > 0)     // 创建孙子进程，让子进程退出，便于回收，孙子进程交给操作系统
                        exit(0);
                    handlerEntery(sock, func);
                    close(sock);
                    exit(0);
                }
                // 父进程
                pid_t ret = waitpid(id, nullptr, 0);
                if (ret > 0)
                {
                    logMessage(NORMAL, "wait child success");
                }
            }
        }

        ~CalServer()
        {
        }

    private:
        int _listensock;
        uint16_t _port;
    };
}